﻿// -----------------------------
// Copyright © Kodi Studios 2012
// -----------------------------

using System;
using System.Data.SqlClient;
using System.Reflection;
using System.ServiceModel;

namespace Aristov.PicturethrillUpdateService
{
    public class UpdateService : IUpdateService
    {
        #region Private Fields
        private readonly Version LatestVersion = Assembly.GetExecutingAssembly().GetName().Version;
        #endregion

        #region Public Methods
        /// <summary>
        /// Returns download path.
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public string GetSetupUrl(Version version)
        {
            // TODO: check whether file exists here
            return "http://picturethrill.com/Downloads/v" + LatestVersion.ToString() + "/PicturethrillSetup.exe";
        }

        /// <summary>
        /// Returns latest version available for download.
        /// </summary>
        /// <returns>Latest version available for download.</returns>
        public Version GetLatestVersion()
        {
            // TODO: Fix up SQL service and reenable this function
            //this.InsertLatestVersionQueryTimestamp();
            return LatestVersion;
        }

        #endregion

        #region Helper Methods

        /// <summary>
        /// Keeps track of how many programs use this service
        /// </summary>
        private void InsertLatestVersionQueryTimestamp()
        {
            DateTime currentTime = DateTime.Now;
            Console.WriteLine(currentTime);
            try
            {
                using (SqlConnection sqlConnection = new SqlConnection())
                {
                    sqlConnection.ConnectionString =
                        @"Server=.\SQLEXPRESS; Trusted_Connection=True; Database=Picturethrill";
                    sqlConnection.Open();

                    using (SqlCommand sqlCommand = new SqlCommand("INSERT INTO LatestVersion VALUES ('" + currentTime.ToString() + "') ", sqlConnection))
                    {
                        sqlCommand.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception e)
            {
                // TODO: Why this exception need to be remapped? Because of WCF?
                throw new FaultException(
                    new FaultReason(e.ToString()),
                    new FaultCode("Data Access Error"));
            }
        }

        #endregion
    }
}
